import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ValidateProvider} from "../../providers/validate/validate";
import {ConfigProvider} from "../../providers/config/config";
import {StorageProvider} from "../../providers/storage/storage";
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {UtilsProvider} from "../../providers/utils/utils";

@IonicPage({
    segment: 'member/collection',
    defaultHistory: ['MemberPage']
})
@Component({
    selector: 'page-collection',
    templateUrl: 'collection.html',
})
export class CollectionPage {

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public validate: ValidateProvider,
        public config: ConfigProvider,
        public storage: StorageProvider,
        public httpService: HttpServicesProvider,
        public util: UtilsProvider
    ) {
    }

    //判断用户是否登录
    ionViewCanEnter(){
        return this.validate.checkLogin();
    }

    userInfo = this.config.userInfoHolder;
    ionViewWillEnter() {
        if (!this.validate.checkLogin()) {//登录
            this.navCtrl.push('LoginPage', {'backPage': 'MemberPage'});
        } else {
            this.getData(null);
        }
    }

    page = 1;
    lists = [];
    getData(infiniteScroll) {
        this.httpService.requestPostData('/story/my_collect', {
            token: this.config.getToken(),
            page: this.page
        }, response => {

            //全部数据
            let data = response['data'];
            // this.lists = this.lists.concat(data['data']);
            this.lists = this.lists.concat(data['lists']);

            this.page++;
            if(infiniteScroll){
                infiniteScroll.complete();   /*请求完成数据更新页面*/
                if(data['lists'].length<data['page_size']){   /*没有数据 禁用上拉更新*/
                    infiniteScroll.enable(false);
                }
            }
        });
    }

    doInfinite(infiniteScroll) {
        this.getData(infiniteScroll);
    }

    /**
     * 删除发布的消息
     * */
    delCollect(amoy_id,index){
        this.util.presentConfirm('确定删除吗？', ()=>{
            let apiUrl = '/task_info/collect_option';
            this.httpService.requestPostData(apiUrl, {
                amoy_id: amoy_id,
                token: this.config.getToken(),
                type: 1
            }, (response)=>{
                if(response['code'] == 200){
                    this.lists.splice(index,1);
                }else{
                    this.util.presentAlert('信息删除失败');
                }
            });
        });
    }
    /**
     * 跳转到信息详情
     * */
    goDetail(amoy_id){
        this.navCtrl.push('ArticleDetailPage', {id: amoy_id});
    }
}
